import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, App } from 'antd';

import { updateUsername } from '@/service/api';

const EditUsernameModal = ({ visible, onCancel, onOk, currentUsername }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const { message } = App.useApp();

  // 当弹框打开时，设置当前用户名为默认值
  useEffect(() => {
    if (visible && currentUsername) {
      form.setFieldsValue({
        nickName: currentUsername
      });
    }
  }, [visible, currentUsername, form]);

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      const [res, err] = await updateUsername({
        nickName: values.nickName
      });
      if (err) {
        message.error(err.message || '修改用户名失败，请重试');
        return;
      }
      
      if (window.OK_CODE === res?.code?.toString()) {
         message.success('用户名修改成功');
         onOk(values.nickName);
       } else {
        message.error(res?.message || '修改用户名失败，请重试');
      }
      
    } catch (error) {
      if (error.errorFields) {
        // 表单验证错误，不需要显示消息
        return;
      }
      message.error('修改用户名失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 取消操作
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  // 验证用户名格式
  const validateUsername = (_, value) => {
    if (!value) {
      return Promise.reject(new Error('请输入用户名'));
    }
    
    // 用户名长度限制
    if (value.length < 2) {
      return Promise.reject(new Error('用户名至少2个字符'));
    }
    
    if (value.length > 20) {
      return Promise.reject(new Error('用户名不能超过20个字符'));
    }
    
    return Promise.resolve();
  };

  return (
    <Modal
      title="修改用户名"
      open={visible}
      onCancel={handleCancel}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
          确认修改
        </Button>,
      ]}
      destroyOnHidden={true}
      width={400}
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Form.Item
          label="用户名"
          name="nickName"
          rules={[
            { validator: validateUsername }
          ]}
          style={{ marginBottom: 16 }}
        >
          <Input 
            placeholder="请输入用户名" 
            maxLength={20}
            showCount
          />
        </Form.Item>
        
        <div style={{ color: '#666', fontSize: '12px', marginTop: '-8px' }}>
          <div>• 用户名长度为2-20个字符</div>
        </div>
      </Form>
    </Modal>
  );
};

export default EditUsernameModal;